// create the module and name it scotchApp
var loginApp = angular.module('loginApp', ['ngResource', 'ngRoute', 'hc.marked']);

// configure our routes
loginApp.config(function($routeProvider) {
    $routeProvider

    // route for the home page
    .when('/', {
        templateUrl: 'app/home/home.html',
        controller: 'homeController'
    })

    // route for the about page
    .when('/manuel', {
        templateUrl: 'app/manuel/manuel.html',
        controller: 'manuelController'
    })

    // route for the about page
    .when('/configure', {
        templateUrl: 'app/configure/configure.html',
        controller: 'configureController'
    })

    // route for the about page
    .when('/graphic', {
        templateUrl: 'app/graphic/graphic.html',
        controller: 'graphicController'
    })

    .when('/register', {
        templateUrl: 'app/register/register.html',
        controller: 'registerController'
    })

    // route for the contact page
    .when('/login', {
        templateUrl: 'app/login/login.html',
        controller: 'loginController'
    });
});

// create the controller and inject Angular's $scope
loginApp.controller('mainController', function($rootScope, $scope, $window, $location, loginService, setBaseService) {

    $scope.isActive = function(viewLocation) {
        return viewLocation === $location.path();
    };

    $scope.logout = function() {
        loginService.logout();
    };

    $scope.setBase = function() {
        // initialise la base dans la session
        setBaseService.get({
            id: $rootScope.databBases.selected
        }, function(configure) {});
    };
});

//this is used to parse the profile
function url_base64_decode(str) {
    var output = str.replace('-', '+').replace('_', '/');
    switch (output.length % 4) {
        case 0:
            break;
        case 2:
            output += '==';
            break;
        case 3:
            output += '=';
            break;
        default:
            throw 'Illegal base64url string!';
    }
    return window.atob(output); //polifyll https://github.com/davidchambers/Base64.js
};

loginApp.factory('authInterceptor', function($rootScope, $q, $window) {
    return {
        request: function(config) {
            config.headers = config.headers || {};
            if ($window.sessionStorage.token) {
                config.headers.Authorization = 'Bearer ' + $window.sessionStorage.token;
            }
            return config;
        },
        responseError: function(rejection) {
            if (rejection.status === 401) {
                // handle the case where the user is not authenticated
            }
            return $q.reject(rejection);
        }
    };
});

loginApp.config(function($httpProvider) {
    $httpProvider.interceptors.push('authInterceptor');
});

loginApp.run(function($rootScope, $location, $log, loginService, configureService) {
    // recuperation des configurations existantes

    $rootScope.currentUser = {};
    $rootScope.databBases = {};
    $rootScope.databBases.selected = 0;
    $rootScope.currentUser.username = loginService.getUserName();
    $rootScope.currentUser.isAuthenticated = loginService.isAuthenticated();
    $rootScope.locationBeforeLogin = '';

    $rootScope.$on('logged in', function() {
        $rootScope.currentUser.username = loginService.getUserName();
        $rootScope.currentUser.isAuthenticated = loginService.isAuthenticated();
        $location.path($rootScope.locationBeforeLogin);
        configureService.query(function(configures) {
            $rootScope.databBases.configures = [];
            for (i = 0; i < configures.length; i++) {
                $rootScope.databBases.configures.push({
                    content: configures[i]['name'],
                    value: configures[i]['_id']
                });
            }
        });
    });

    $rootScope.$on('logged out', function() {
        $rootScope.currentUser.username = loginService.getUserName();
        $rootScope.currentUser.isAuthenticated = loginService.isAuthenticated();
    });

    $rootScope.$on('configure change', function() {
        configureService.query(function(configures) {
            $rootScope.databBases.configures = [];
            for (i = 0; i < configures.length; i++) {
                $rootScope.databBases.configures.push({
                    content: configures[i]['name'],
                    value: configures[i]['_id']
                });
            }
        });
    });

    $rootScope.$on('$locationChangeStart', function(event, next, current) {
        if ($location.path() != '/login' && $location.path() != '/register') {
            if (!loginService.isAuthenticated()) {
                // user is not authentified
                $rootScope.locationBeforeLogin = $location.path();
                $location.path('/login');
            }
        }
    });
});